package com.tyf.common.web.controller;

import com.tyf.common.service.MongoFileService;
import com.tyf.common.vo.SystemUser;
import com.tyf.common.web.bind.annotation.CurrentUser;
import me.lightspeed7.mongofs.MongoFile;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;

/**
 * 文件下载
 */
@Controller
public class DownloadController {
	@Resource
	private MongoFileService mongodbManager;
	
	private static final Logger logger = LoggerFactory.getLogger(DownloadController.class);

	/**
	 * 网格导出
	 * @param user
	 * @param request
	 * @param response
	 * @param fileurl
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download")
	public String download(@CurrentUser SystemUser user, HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fileurl") String fileurl) throws Exception {
		if (StringUtils.isEmpty(fileurl) || fileurl.contains("\\.\\.")) {
			response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("您下载的文件不存在！");
            return null;
        }
        //mongodb集合名称
		String tableName = request.getParameter("tableName");
		ByteArrayOutputStream out = null;
		byte[] bytes = null;
		String fileName = "";
		try {
			 out = new ByteArrayOutputStream();

			MongoFile mgFile = null;
			if(StringUtils.isNotEmpty(tableName)){
				//集合名称，mongodb
				mgFile = mongodbManager.findOne(tableName,fileurl);
			}else{
				mgFile = mongodbManager.findOne(fileurl);
			}

			mgFile.readInto(out, true);
			bytes = out.toByteArray();
			fileName = mgFile.getFilename(); //文件名称
			
			if(bytes == null){
				response.setContentType("text/html;charset=utf-8");
	            response.setCharacterEncoding("utf-8");
	            response.getWriter().write("未读取到对应的文件,FileUrl:【"+fileurl+"】");
				return null;
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
			response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("未读取到对应的文件,FileUrl:【"+fileurl+"】");
            return null;
		}finally {
			IOUtils.closeQuietly(out);
		}
		
		String userAgent = request.getHeader("User-Agent");
        boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

        response.reset();
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "must-revalidate, no-transform");
        response.setDateHeader("Expires", 0L);

        response.setContentType("application/x-download");
        response.setContentLength((int) bytes.length);

        if (isIE) {
        	fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        } else {
        	fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        }
		response.getOutputStream().write(bytes);
		
		return null;
	}

}
